#include <func.h>

void cleanup(void* arg) {
    char* message = (char*)arg;
    printf("cleanup: %s\n", message);
}

void* start_routine(void* arg) {
    // 每个线程都有自己的清理函数栈
    pthread_cleanup_push(cleanup, "first");
    pthread_cleanup_push(cleanup, "second");
    pthread_cleanup_push(cleanup, "third");
    
    /* pthread_exit(NULL); // 会执行 */
    /* return NULL;    // 不会执行 */
    
    pthread_cleanup_pop(9);   // 执行线程清理函数，但不会导致线程终止

    printf("new thread: begin\n");

    for(;;) {
        pthread_testcancel();
    }

    // 肯定不会执行
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
}

int main(int argc, char* argv[])
{
    pthread_t tid;
    pthread_create(&tid, NULL, start_routine, NULL);

    sleep(1);

    pthread_cancel(tid);    // 发送取消请求

    pthread_join(tid, NULL);

    return 0;
}

